package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.OSSAliyunFileStorageService;
import com.heima.model.common.constants.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    OSSAliyunFileStorageService storageService;

    @Value("${file.oss.profix}")
    private String profix;
    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 上传图片接口
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile file) {
        //1 参数校验
        if (file == null || file.getSize() == 0 ) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2 获取登录用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }


        //3 上传到OSS
        // 原始文件名称
        String originalFilename = file.getOriginalFilename();

        String newFileName = UUID.randomUUID().toString().replace("-", "");
        // 文件后缀
        String postFix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = storageService.store(profix, newFileName + postFix, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl file upload error:{}", e);
            CustException.cust(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }


        //4 文件信息保存WmMaterial
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection(WemediaConstants.IS_NO_COLLECTION);
        wmMaterial.setType(WemediaConstants.PICTURE_TYPE);

        if (StringUtils.isBlank(fileId)) {
            CustException.cust(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }
        wmMaterial.setUrl(fileId);
        // 设置登录用户
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);


        //5 返回结果
        // 给文件图片加访问前缀
        wmMaterial.setUrl(webSite + fileId);

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 根据token中的user信息，查看user对应的素材
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 1 参数校验
        dto.checkParam();
        // 2 执行业务查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        // 收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        // 当前登录用户的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wrapper.eq(WmMaterial::getUserId, user.getId());

        // 时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageParam = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> resultPage = page(pageParam, wrapper);

        // 处理图片
        List<WmMaterial> wmMaterials = resultPage.getRecords();
        for (WmMaterial wmMaterial : wmMaterials) {
            wmMaterial.setUrl(webSite + wmMaterial.getUrl());
        }
        // 3 封装结果
        return new PageResponseResult(dto.getPage(), dto.getSize(),
                resultPage.getTotal(), resultPage.getRecords());
    }


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult delPicture(Integer id) {
        // 1 参数校验
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
//        int i = 1/0;
        // 2 业务处理
        // 判断当前id是否被引用，如果被使用则禁止删除
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count > 0) {
            throw new CustomException(AppHttpCodeEnum.FILE_DELETE_ERROR);
        }
        // 删除图片OSS
        storageService.delete(wmMaterial.getUrl());
        // 删除素材库
        removeById(id);

        // 3 封装结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.更新状态
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection, type)
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, uid));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
